#!/usr/bin/env python
# encoding: utf-8

import tornado.gen
import httplib2
import urllib
import json
import hashlib
import traceback
import os

ROOT_DIR = "/home/"

class AutodeployModel():
    def __init__(self):
        print "this is init for AutodeployModel"

    def __get_message_by_msgtype(self, msgtype, data, cellphone_list, msg_contents):
        message_dict = {}
        if 'text' == msgtype:
            contents_dict = {}
            atMobiles_dict = {}
            atMobiles_dict['atMobiles'] = cellphone_list
            atMobiles_dict['isAtAll'] = 'true'
            contents_dict['content'] = msg_contents
            message_dict['msgtype'] = 'text'
            message_dict['text'] = contents_dict
            message_dict['at'] = atMobiles_dict
        elif 'link' == msgtype:
            link_contents_dict = {}
            link_contents_dict['text'] = msg_contents
            link_contents_dict['title'] = u"码云平台 - " + data['project']['path_with_namespace']
            link_contents_dict['picUrl'] = ""
            link_contents_dict['messageUrl'] = data['commits'][0]['url']

            message_dict = {}
            message_dict['msgtype'] = 'link'
            message_dict['link'] = link_contents_dict
        message_dict['projectname'] = data['project']['name']
        message_dict['git_pull_status_value'] = data['git_pull_status_value']
        return message_dict


    @tornado.gen.coroutine
    def fnPush(self, data):
        ret = True
        try:
            message = {}
            title_name = ''
            project_dir = ''
            cellphone_list = []
            restart_info = ''
            if "advertisement_backend" == data['project']['name']:
                title_name = u'后端程序更新'
                cellphone_list.extend(['18200113256','18782932495'])
                project_dir = 'advertisement_backend'
                restart_info = u',30秒后后台服务程序会重启'
            if 'AdsManageSystem' == data['project']['name']:
                title_name = u'前端程序更新'
                cellphone_list.extend(['18782932495'])
                project_dir = 'AdsManageSystem'
            if u"广告系统后台项目开发文档" == data['project']['name']:
                title_name = u'后端API文档更新'
                cellphone_list.extend(['18782932495'])
            git_pull_status = self.__git_pull_code(project_dir)

            if u"广告系统后台项目开发文档" == data['project']['name']:
                data['git_pull_status'] = ''
            else:
                data['git_pull_status'] = u'测试服务器代码更新状态:'
                data['git_pull_status'] += u'成功{0}'.format(restart_info) if 0 == git_pull_status else u'失败'
            data['git_pull_status_value'] = git_pull_status

            msg_contents = title_name + ":" + str(data['total_commits_count']) + " new commit " + "by " + \
                           data['user_name'] + "\n " \
                           + u"注释: " + data['commits'][0]['message'] + "\n" \
                           + u"提交时间: " + data['user']['time'] + "\n" \
                           + data['git_pull_status'] + "\n"

            message = self.__get_message_by_msgtype('text', data, cellphone_list, msg_contents)
            print message
            print type(message)
        except Exception as e:
            print ("Exception occur in fnPush %s" % e)
            ret = False
        finally:
            if ret:
                return message

    @tornado.gen.coroutine
    def send_message_to_dingtalk(self, data):
        ret = True
        try:
            hosturl_slave = ''
            if "advertisement_backend" in data['projectname']:
                hosturl_slave = "https://oapi.dingtalk.com/robot/send?access_token=2ab447c0ef053ee1a19e74422f88376dddef11404286330f37bd7418ccb6c39d"
            if "AdsManageSystem" in data['projectname']:
                hosturl_slave = "https://oapi.dingtalk.com/robot/send?access_token=2ab447c0ef053ee1a19e74422f88376dddef11404286330f37bd7418ccb6c39d"
            if u"广告系统后台项目开发文档" in data['projectname']:
                hosturl_slave = "https://oapi.dingtalk.com/robot/send?access_token=2ab447c0ef053ee1a19e74422f88376dddef11404286330f37bd7418ccb6c39d"
            data = json.dumps(data)
            headers = {"Content-type": "application/json","Accept": "text/plain"}
            conn = httplib2.Http(".cache")
            if hosturl_slave is not None:
                response,content = conn.request(hosturl_slave, 'POST',data, headers)
                print content.decode('utf-8')
        except Exception as e:
            print "Exception occur in send_message_to_dingtalk %s" % e
            ret = False
        finally:
            if ret:
                print "success"

    def __git_pull_code(self, project_dir):
        if not project_dir:
            return 0
        print "git pull {0}".format(project_dir)
        status = os.system("cd {1}{0} && git pull".format(project_dir, ROOT_DIR))
        print "git pull cmd status={0}".format(status)
        return status

    def restart_advertisement_backend(self, project_dir, data, git_pull_status):
        print "restart_advertisement_backend"
        if (0 == git_pull_status) and ("advertisement_backend" == data['project']['name']):
            str = os.popen("cd {1}{0} && supervisorctl restart advertisement_backend".format(project_dir, ROOT_DIR)).read()
            print str
            cellphone_list = ['18200113256', '18782932495']
            if 'started' in str:
                msg_contents = u'后台服务程序重启状态：成功 \n'
            else:
                msg_contents = u'后台服务程序重启状态：失败 \n'
            message = self.__get_message_by_msgtype('text', data, cellphone_list, msg_contents)
            self.send_message_to_dingtalk(message)

    # @tornado.gen.coroutine
    # def check_auth(self, data):
    #     ret = True
    #     try:
    #         name = data['terminal_name']
    #         timestramp = str(data['timestramp'])
    #         password = data['auth']
    #         name = bytes(name, encoding = "utf8")
    #         timestramp = bytes(timestramp, encoding = "utf8")
    #         #print(type(name))
    #         #print(type(timestramp))
    #         m = hashlib.md5()
    #         m.update(name)
    #         m.update(timestramp)
    #         m.update(b"6sB<n8PpZ{}chV5yUB7a")
    #         md5value=m.hexdigest()
    #         #print(md5value)
    #         if password==md5value:
    #             print("check ok")
    #             ret = True
    #         else:
    #             print("check failed %s" % data['terminal_name'])
    #             ret = False
    #     except Exception as e:
    #         print ("Exception occur in check_auth %s" % e)
    #         print('traceback.format_exc():\n%s' % traceback.format_exc())
    #         ret = False
    #     finally:
    #         if ret:
    #             print ("success")
    #         return ret

    # # @tornado.gen.coroutine
    # def get_ctl_result(self, data):
    #     terminal_list = []
    #     ret = True
    #     try:
    #         ret = yield self.check_auth(data)
    #         if ret:
    #             with open("remotectl.conf","r",encoding="utf-8") as f:
    #                 lines = f.readlines()
    #                 for line in lines:
    #                     print line
    #                     terminal_list.append(line)
    #         else:
    #             ret = False
    #     except Exception as e:
    #         print "Exception occur in get_ctl_result %s" % e
    #         print 'traceback.format_exc():\n%s' % traceback.format_exc()
    #         ret = False
    #     finally:
    #         if ret:
    #             print "get_ctl_result success"
    #             return terminal_list
    #
    # # @tornado.gen.coroutine
    # def disable_remote_access_by_terminal_name(self, data):
    #     ret = True
    #     try:
    #         ret = yield self.check_auth(data)
    #         if ret:
    #             with open("remotectl.conf","r",encoding="utf-8") as f:
    #                 lines = f.readlines()
    #                 #print(lines)
    #             with open("remotectl.conf","w",encoding="utf-8") as f_w:
    #                 for line in lines:
    #                     if data['terminal_name'] in line:
    #                         continue
    #                     f_w.write(line)
    #         else:
    #             ret = False
    #     except Exception as e:
    #         print ("Exception occur in get_ctl_result %s" % e)
    #         print('traceback.format_exc():\n%s' % traceback.format_exc())
    #         ret = False
    #     finally:
    #         if ret:
    #             print ("disable_remote_access_by_terminal_name success")
    #         return ret

